import importlib

#中介者X
class MediatorX:

    _containers = {}
    _instance = None

    def __init__(self):
        pass

    #单例
    @staticmethod
    def instance():
        if not MediatorX._instance:
            MediatorX._instance = MediatorX()
        return MediatorX._instance

    #注册
    def register(self,route, cls):

        if route not in self._containers:
            self._containers[route] = []

        self._containers[route].append(cls)

    def register_by_class(self, route, class_full_name):

        # 反射调用
        last_index_rfind = class_full_name.rfind('.')
        class_name_length = len(class_full_name)

        namespace_name = class_full_name[:last_index_rfind]
        class_name = class_full_name[last_index_rfind + 1:class_name_length]

        module = importlib.import_module(namespace_name)
        class_obj = getattr(module, class_name, None)  # 不存在则为None

        self.register(route, class_obj)


    def execute(self, route,data):

        if route not in self._containers:
            pass

        for item in self._containers[route]:
            try:
                item.handler(data)
            except Exception as e:
                # 异常处理代码
                print(e)


if __name__ == '__main__':
    MediatorX.instance().register_by_class('api/test', 'Evetns.test.TestEvetns')
    MediatorX.instance().register_by_class('api/test', 'Evetns.test.TestEvetns2')

    MediatorX.instance().execute('api/test', '好玩的')